﻿using Autofac;
using Autofac.Builder;
using AutoRegistDependency.Component;
using AutoRegistDependency.Enum;
using AutoRegistDependency.Implement;
using AutoRegistDependency.Utils;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoRegistDependency.RegistrationHandler
{
    /// <summary>
    /// 泛型聚合服务处理
    /// Generic aggregation service processing
    /// </summary>
    internal class GenericAggregateServiceHandler : AbstractRegistrationHandler
    {
        public override bool CanRegister(ComponentDefinition component)
        {
            return component.ComponentType == ComponentType.AggregateService && component.InjectType.IsGenericType;
        }

        protected override IRegistrationBuilder<object, object, object> Register(ContainerBuilder containerBuilder, ComponentDefinition component)
        {
            var register = containerBuilder.RegisterGeneric((c, types) =>
            {
                return AutoFacHelper.CreateProxyInstance(new AggregateServiceInterceptor(c.Resolve<IComponentContext>(), component.InjectType.MakeGenericType(types), component), component.InjectType);
            });
            return register;
        }
        public override IRegistrationBuilder<object, object, object> StartRegistration(ContainerBuilder containerBuilder, ComponentDefinition component, bool isInterface, Type[] types, bool hasPostProcessor, HostBuilderContext hostBuilderContext)
        {
            if (CanRegister(component))
            {
                var registrationBuilder = Register(containerBuilder,component);
                RegistrationAs(registrationBuilder,component,types);
                registrationBuilder.OnlyIf(componentRegistry => ShouldRegistration(component,hostBuilderContext, componentRegistry));
                return registrationBuilder;
            }
            else
            {
                return NextHandler?.StartRegistration(containerBuilder, component, isInterface, types, hasPostProcessor, hostBuilderContext);
            }           
        }
    }
}
